package com.alstudio.utils.android.net.http.http2;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;

import android.net.http.AndroidHttpClient;

public class HttpPostRequest {

	public static final String TAG = HttpPostRequest.class.getSimpleName();

	private String url;
	private HttpParameters params = null;
	private HttpParameters headers = null;
	private AndroidHttpClient client;
	private HttpPost postMethod;

	public HttpPostRequest(String url) {
		this.url = url;
	}

	public void addHeader(String name, String value) {
		if (headers == null)
			headers = new HttpParameters();

		headers.add(name, value);
	}

	public void addParameter(String name, String value) {
		if (params == null)
			params = new HttpParameters();

		params.add(name, value);
	}

	public void request(IHttpHandler handler) {
		postMethod = new HttpPost(url);
		try {
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
					params.value(), "UTF-8");
			postMethod.setEntity(entity);

			if (headers != null) {
				for (int i = 0; i < headers.size(); ++i) {
					postMethod
							.setHeader(headers.getKey(i), headers.getValue(i));
				}
			}

			client = AndroidHttpClient.newInstance("");

			HttpResponse response = client.execute(postMethod);

			if (handler != null) {
				handler.handleResponse(response);
			}

		} catch (IOException e) {
			if (handler != null) {

				handler.handleException(e);
			}

		} finally {
			client.close();
		}

	}

	public void requestAsync(final IHttpHandler handler) {
		new Thread() {

			@Override
			public void run() {
				request(handler);
			}

		}.start();
	}

	public void cancel() {
		if (postMethod != null)
			postMethod.abort();

		if (client != null)
			client.close();
	}
}
